import { Button, Form, Input, Modal, Popconfirm, Space, Switch, Table } from "antd"
import { useForm } from "antd/es/form/Form";
import { useContext, useState } from "react"
import { StateEnum } from "./reducer";
import { ListContext, ListDispatchContext } from "./context";

type FieldType = Partial<StateEnum>

function ListChild() {
  const [row, setRow] = useState({})
  const [form] = useForm()
  const dataSource = useContext(ListContext)!
  const dispatch = useContext(ListDispatchContext)!

  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = (record: { id: number, text: string, state: boolean}) => {
    setIsModalOpen(true);
    setRow(record)
    form.setFieldsValue(record)
  };

  const handleOk = () => {
    setIsModalOpen(false);
    // console.log(form.getFieldsValue())
    dispatch({
      type: 'CHANGE',
      listItem: {...row, ...form.getFieldsValue()}
    })
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleDelete = (key: number) => {
    dispatch({
      type: 'DELETE',
      listItem: { id: key }
    })
  }

  const columns = [
    {
      title: '编码',
      dataIndex: 'id',
    },
    {
      title: '名称',
      dataIndex: 'text',
    },
    {
      title: '状态',
      dataIndex: 'state',
      render: (text: boolean, _record: { id: number, text: string, state: boolean}, index: number) => {
        return text ? '状态是' : '状态否'
      }
    },
    {
      title: '操作',
      render: (_: any, record: { id: number, text: string, state: boolean}) => {
        return (
          <Space>
            <Button type="link" block onClick={() => showModal(record)}>编辑</Button>
            <Popconfirm title="确认删除?" onConfirm={() => handleDelete(record.id)}>
              <Button type="text" danger>删除</Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  return (
    <div>
      <Table rowKey={'id'} dataSource={dataSource} columns={columns} />

      <Modal title="Basic Modal" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          layout="vertical"
          style={{ maxWidth: 600 }}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="名称"
            name="text"
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item label="状态" name={'state'} valuePropName="checked">
            <Switch />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default ListChild